package com.ljb.autosize;

import android.content.Context;
import android.util.Log;
import android.util.TypedValue;
import android.view.WindowManager;
import android.widget.TextView;

/**
 * Created by lijianbin on 2016/12/8.
 */
public class AutoSize {
    /**
     * 1,使用前必须确定设计模板的尺寸
     * 2,在Activity的onCreate方法当中调用init()进行初始化
     * 3,为TextView设置大小的时候,调用autoTextView()方法进行
     */
    private static int design_width = 720;
    private static int design_height = 1280;

    private static double width_per;
    private static double height_per;
    private static int width;
    private static int height;

    public static void init(Context mContext) {
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();

        if (width == 0 || height == 0) {
            try {
                throw new Throwable("没有获取到屏幕的宽高");
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        } else {
            width_per = (double) width / design_width;
            height_per = (double) height / design_height;
            Log.i("AutoSize:", "屏幕的宽为:" + width + "屏幕高为:" + height);
            Log.i("AutoSize:", "屏幕宽的比率是:" + width_per + "屏幕高的比率是:" + height_per);
        }
    }

    /**
     * 适配宽
     *
     * @param size
     * @return
     */
    public static int autoWeight(int size) {
        int autoSize = (int) (width_per * size);
        Log.i("AutoSize:适配后的width为:", autoSize + "");
        return autoSize;
    }

    /**
     * 设配高
     *
     * @param size
     * @return
     */
    public static int autoHeight(int size) {
        int autoSize = (int) (height_per * size);
        Log.i("AutoSize:适配后的height为:", autoSize + "");
        return autoSize;
    }

    /**
     * 适配TextView字体
     *
     * @param view
     * @param size
     * @return
     */
    public static void autoTextView(TextView view, float size) {
        view.setTextSize(TypedValue.COMPLEX_UNIT_PX, autoSize(size));
    }

    private static float autoSize(float size) {
        float autoSize = (float) (width_per * size);
        Log.i("AutoSize:适配后的size为:", autoSize + "");
        return autoSize;
    }
}
